package ydzhao.weixin.tuisong.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chlong
 * @date 2022/8/2
 */
@Slf4j
public class IpUtil {
    private static String key = "xxx";
    private static String urls = "http://apis.map.qq.com/ws/location/v1/ip?key=";   //腾讯位置api,此处暂未使用到

    /**
     * 通过网络获取用户IP地址
     * @return
     */
    public static Map<String,String> getIpAddress() {
        Map<String,String> map = new HashMap<>();
        try {   //腾讯IP定位（普通）接口  10,000次/日   5次/秒
            JSONObject jsonObject = JSON.parseObject(HttpUtil.getUrl(urls+key));
            if (jsonObject != null && !jsonObject.isEmpty() && jsonObject.getIntValue("status") == 0) {
                jsonObject.getJSONObject("result").getJSONObject("ad_info").getString("province");
                String province = jsonObject.getJSONObject("result").getJSONObject("ad_info").getString("province");
                String city = jsonObject.getJSONObject("result").getJSONObject("ad_info").getString("city");
                map.put("province",province);
                map.put("city",city);
            }
        } catch (Exception e) { }
        return map;
    }

    public static void main(String[] args) {
        Map<String, String> address = getIpAddress();
        log.info("ip->{}",address);
    }
}
